import Taro, { showModal as ShowModal } from '@tarojs/taro'

export function isWechat() {
    return process.env.TARO_ENV === 'weapp'
}

export function getTime() {
    return Math.floor(((new Date()).getTime()) / 1000)
}

export function reducer(state, action) {
    let keys = Object.keys(action)
    let values = Object.values(action)
    keys.forEach((key, index) => {
        state[key] = values[index]
    })
    return {...state}
}


export function showToast(title:string) {
    return Taro.showToast({
        title,
        icon : 'none'
    })
}

export function showLoading(title:string = '') {
    Taro.showLoading({
        title,
        mask : true
    })
}

export function hideLoading() {
    Taro.hideLoading()
}

export function showModal(params: ShowModal.Option|string) {
    let option:ShowModal.Option = {
        
    }
    if(typeof params == 'string') {
        option.content = params
        option.showCancel = false
    }else {
        option = Object.assign(option, params)
    }

    Taro.showModal(option)
}


export function formatTime(time) {
    let date1 = new Date(time * 1000)
    let toDay = new Date()
    let y1:any = date1.getFullYear()
    let m1:any = date1.getMonth() + 1
    let d1:any = date1.getDate()
  
    let y:any = toDay.getFullYear()
    let m:any = toDay.getMonth() + 1
    let d:any = toDay.getDate()
    let offset = Math.ceil(toDay.getTime() / 1000 - time)
    if (offset < 3600 * 24){ //小于一天
      if(offset < 3600){
        let v = Math.floor(offset / 60)
        return  v < 5 ? '刚刚' : v + '分钟前'
      }else{
        return Math.floor(offset / 3600) + '小时前'
      }
      
    }else{
      if ((y1 + m1 + d1) === (y + m + d)) { //同一天
        let h:any = date1.getHours()
        let miu:any = date1.getMinutes()
        if (h < 10) {
          h = '0' + h
        }
  
        if (h < 10) {
          miu = '0' + miu
        }
  
        return h + ':' + miu
      } else if (y1 == y){ //同一年
        if (m1 < 10) {
          m1 = '0' + m1
        }
  
        if (d1 < 10) {
          d1 = '0' + d1
        }
  
        let h = date1.getHours()
        let miu:any = date1.getMinutes()
        if (h < 10) {
          h = '0' + h
        }
  
        if (h < 10) {
          miu = '0' + miu
        }
  
        return m1 + '-' + d1 + ' ' + h + ':' + miu
      }
    }
  
    if (m < 10) {
      m = '0' + m
    }
  
    if (d < 10) {
      d = '0' + d
    }
  
    return y + '-' + m + '-' + d
  
  }